package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.VideoFilterAdapter;
import flc.ast.bean.MyVideoFilterBean;
import flc.ast.databinding.ActivityVideoFilterBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FastClickUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoFilterActivity extends BaseAc<ActivityVideoFilterBinding> {

    public static String videoPath;
    private Dialog myTipDialog;
    private String oldPath = "";
    private VideoFilterAdapter filterAdapter;
    private int oldPosition = 0;
    private boolean isFilter = false;
    private String filter = "";

    @Override
    protected int onCreate() {
        return R.layout.activity_video_filter;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoFilterBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.tvGenerate.setOnClickListener(this);
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.ivVideoFilterSave.setOnClickListener(this);
        mDataBinding.rvVideoFilterList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        filterAdapter = new VideoFilterAdapter();
        mDataBinding.rvVideoFilterList.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(this);
        //提示弹框
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        if (FastClickUtil.isFastClick()) return;
        switch (v.getId()){
            case R.id.ivVideoPlay:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang00);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting00);
                    mDataBinding.videoView.start();
                }
                break;
            case R.id.tvGenerate:
                if (TextUtils.isEmpty(filter)) {
                    //设置原图
                    setPlayer();
                    ToastUtils.showShort(getString(R.string.generate_suc));

                } else {
                    //添加滤镜
                    filterVideo();
                }
                break;
            case R.id.ivVideoFilterSave:
                if (!isFilter){
                    ToastUtils.showShort(getString(R.string.please_generate));
                    return;
                }
                saveVideo();
                break;
            //提示弹框
            case R.id.tvDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
            case R.id.tvDialogTipRight://确定
                myTipDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        filterAdapter.getItem(oldPosition).setSelect(false);
        filterAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        filterAdapter.getItem(position).setSelect(true);
        filterAdapter.notifyItemChanged(position);
        //设置滤镜
        filter = filterAdapter.getItem(position).getFilter();
        //重置路径 --避免叠加
        videoPath = oldPath;
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(videoPath)) return;
        oldPath=videoPath;
        setPlayer();
        List<MyVideoFilterBean> listFilter = new ArrayList<>();
        listFilter.add(new MyVideoFilterBean("", getString(R.string.filter_text1), "#00000000", true));
        listFilter.add(new MyVideoFilterBean("lutyuv='u=128:v=128'", getString(R.string.filter_text2), "#323333", false));
        listFilter.add(new MyVideoFilterBean("hue='h=60:s=-3'", getString(R.string.filter_text3), "#C376F3", false));
        listFilter.add(new MyVideoFilterBean("lutyuv='y=maxval+minval-val:u=maxval+minval-val:v=maxval+minval-val'", getString(R.string.filter_text4), "#6F7171", false));
        listFilter.add(new MyVideoFilterBean("lutyuv=y=negval", getString(R.string.filter_text5), "#505151", false));
        listFilter.add(new MyVideoFilterBean("lutyuv='u=128:v=128'", getString(R.string.filter_text7), "#999999", false));
        listFilter.add(new MyVideoFilterBean("lutyuv='y=2*val'", getString(R.string.filter_text8), "#513232", false));
        listFilter.add(new MyVideoFilterBean("unsharp", getString(R.string.filter_text9), "#787A7A", false));
        filterAdapter.setList(listFilter);
    }

    //添加滤镜
    private void filterVideo() {
        EpVideo epVideo = new EpVideo(videoPath);
        epVideo.addFilter(filter);
        String path = FileUtil.generateFilePath(Content.myTemp, ".mp4", videoPath);
        EpEditor.OutputOption outputOption = new EpEditor.OutputOption(path);
        EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        isFilter = true;
                        videoPath = path;
                        ToastUtils.showShort(getString(R.string.generate_suc));
                        //设置播放器
                        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting00);
                        mDataBinding.videoView.setVideoPath(videoPath);
                        mDataBinding.videoView.seekTo(1);
                        mDataBinding.videoView.start();
                    }
                });
            }

            @Override
            public void onFailure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        ToastUtils.showShort(R.string.add_filter_def);
                    }
                });
            }

            @Override
            public void onProgress(float progress) {
                float v = progress * 100;
                if (v < 0) {
                    v = 0;
                } else if (v > 100) {
                    v = 100;
                }
                showDialog(getString(R.string.add_filter_ing) + new DecimalFormat("#.0").format(v) + "%");
            }
        });
    }

    //保存视频
    private void saveVideo() {
        showDialog(getString(R.string.save_video_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, videoPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_suc);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    //设置播放器
    private void setPlayer() {
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang00);
                mp.seekTo(1);
            }
        });
        //开始播放视频
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting00);
        mDataBinding.videoView.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang00);
        mDataBinding.videoView.pause();
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y=50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogTipCancel);
        TextView right = inflate.findViewById(R.id.tvDialogTipRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}